using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Castle.DynamicProxy;
using EntityAop.Interceptors;

namespace EntityAop
{
    public class InterceptorSelector : IInterceptorSelector
    {
        private static Type SetNotifyingInterceptorType = typeof(SetNotifyingInterceptor);
        private static Type EqualsInterceptorType = typeof(EqualsInterceptor);
        private static Type TargetAccessorInterceptorType = typeof (TargetAccessorInterceptor);

        private static List<Type> ExcludedTypes = new List<Type>()
                                                      {
                                                          SetNotifyingInterceptorType, 
                                                          EqualsInterceptorType,
                                                          TargetAccessorInterceptorType
                                                      };


        public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
        {
            if (method.Name.StartsWith("set_"))
            {
                return SelectInterceptors(interceptors, SetNotifyingInterceptorType);
            }

            if (method.Name == "Equals")
            {
                return SelectInterceptors(interceptors, EqualsInterceptorType);
            }

            if (method.Name == "GetTarget")
            {
                return SelectInterceptors(interceptors, TargetAccessorInterceptorType);
            }

            return interceptors.Where(
                    interceptor => !ExcludedTypes.Contains(interceptor.GetType()))
                .ToArray();
        }

        private static IInterceptor[] SelectInterceptors(IInterceptor[] interceptors, Type interceptorType)
        {
            return interceptors.Where(interceptor => interceptor.GetType() == interceptorType).ToArray();
        }
    }
}